#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/7/2 13:44
# @Author : wn 
# @File: datasearch.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡

import json

from django.shortcuts import render
from django.views import View

from trade.search_page import *
from utils.service import my_page
import datetime


class Query(View):
    def get(self, request):
        # 当前在第几页
        off = request.GET.get('offset', None)
        # 一页几条
        lim = request.GET.get('limit', None)
        stgname = ''
        if lim is None:
            return render(request, 'query.html', {'url': '/trade/query'})
        else:
            tab_type = request.GET.get('type')
            today = datetime.datetime.now().strftime("%Y%m%d")
            todayi = datetime.datetime.now().strftime("%Y-%m-%d")
            # t_ruleorder 订单
            ro_list = list(Ruleorder.objects.using('quantPaperDB').filter(tradingday=today).values())
            for item in ro_list:
                item['direction'] = Direction_ModelChoices.get(item['direction'], None)
                item['legsettltype'] = LegSettlType_ModelChoices.get(item['legsettltype'], None)
                item['reserver1'] = Reserver1_ModelChoices.get(item['reserver1'], None)
                # item['reserver2'] = Reserver2_ModelChoices.get(item['reserver2'], None)
                item['orderstatus'] = OrderStatus_Choices.get(item['orderstatus'], None)
                stg = Strategy.objects.using('quantWebDB').filter(stgid=item["ruleid"])
                if len(stg) != 0:
                    stgname = stg[0].stgname
                item['rulename'] = stgname
            # t_ruletrade 成交
            rt_list = list(Ruletrade.objects.using('quantPaperDB').filter(tradingday=today).values())
            for item in rt_list:
                item['direction'] = Direction_ModelChoices.get(item['direction'], None)
                item['legsettltype'] = LegSettlType_ModelChoices.get(item['legsettltype'], None)
                stg = Strategy.objects.using('quantWebDB').filter(stgid=item["ruleid"])
                if len(stg) != 0:
                    stgname = stg[0].stgname
                item['rulename'] = stgname
            # t_ruleposition 持仓
            rp_list = []
            rp_qs = Ruleposition.objects.using('quantPaperDB').filter(tradingday=today)
            for item in rp_qs:
                rp_dict = {}
                rp_dict['ruleid'] = item.ruleid
                rp_dict['position'] = item.position
                rp_dict['instrumentid'] = item.instrumentid

                stg = Strategy.objects.using('quantWebDB').filter(stgid=item.ruleid)
                if len(stg) != 0:
                    stgname = stg[0].stgname
                rp_dict['rulename'] = stgname
                rp_list.append(rp_dict)

            # t_papermanualtrade 录入
            rm_list = list(
                ManualTradePaper.objects.using('quantWebDB').filter(transactime__startswith=todayi).order_by('-transactime').values())
            for item in rm_list:
                stg = Strategy.objects.using('quantWebDB').filter(stgid=item["ruleid"])
                item['direction'] = Direction_ModelChoices.get(item['direction'], None)
                item['settletype'] = LegSettlType_ModelChoices.get(item['settletype'], None)
                if len(stg) != 0:
                    stgname = stg[0].stgname
                item["stgname"] = stgname

            result_list_sorted = []
            if tab_type == '0':
                # 排序 Ruleorder
                for item in ro_list:
                    if (item.get('orderinnerid') is None):
                        item['orderinnerid'] = '-1'
                result_list_sorted = sorted(ro_list, key=itemgetter('orderinnerid'), reverse=True)
            elif tab_type == '1':
                # 排序 Ruletrade
                for item in rt_list:
                    if (item.get('tradeid') is None):
                        item['tradeid'] = '-1'
                result_list_sorted = sorted(rt_list, key=itemgetter('tradeid'), reverse=True)
            elif tab_type == '2':
                # 排序 Ruleposition
                for item in rp_list:
                    if (item.get('ruleid') is None):
                        item['ruleid'] = '-1'
                result_list_sorted = sorted(rp_list, key=itemgetter('ruleid'), reverse=False)
            elif tab_type == '3':
                # 排序 录入
                for item in rm_list:
                    if (item.get('transactime') is None):
                        item['transactime'] = '-1'
                result_list_sorted = sorted(rm_list, key=itemgetter('transactime'), reverse=True)

            result = my_page(result_list_sorted, lim, off)
            return JsonResponse(result)

    def post(self, request):
        if request.POST.get("daySearchOrder_search", None):
            # 前端查询条件
            data = json.loads(request.POST.get("data"))
            instrumentid = data.get("instrumentid", None)  # if no condition value is str ''
            direction = data.get("direction", None)  # str ''
            legsettltype = data.get("legsettltype", None)
            orderinnerid = data.get("orderinnerid", None)
            ordersysid = data.get("ordersysid", None)
            ruleid = data.get("ruleid", None)
            pl_envid = data.get("pl_envid", None)
            if pl_envid == "1":  # 仿真环境
                jsonRes = search_daySearch(instrumentid=instrumentid, direction=direction, legsettltype=legsettltype,
                                           orderinnerid=orderinnerid, ordersysid=ordersysid, ruleid=ruleid, type='0')
            elif pl_envid == "2":  # 实盘环境
                jsonRes = search_liveSearch(instrumentid=instrumentid, direction=direction, legsettltype=legsettltype,
                                            orderinnerid=orderinnerid, ordersysid=ordersysid, ruleid=ruleid, type='0')
            return jsonRes
        elif request.POST.get('daySearchTrade_search', None):
            # 前端查询条件
            data = json.loads(request.POST.get("data"))
            instrumentid = data.get("instrumentid", None)  # if no condition value is str ''
            direction = data.get("direction", None)  # str ''
            legsettltype = data.get("legsettltype", None)
            tradeid = data.get("tradeid", None)
            ruleid = data.get("ruleid", None)
            pl_envid = data.get("pl_envid", None)
            if pl_envid == "1":  # 仿真环境
                jsonRes = search_daySearch(instrumentid=instrumentid, direction=direction, legsettltype=legsettltype,
                                           tradeid=tradeid, ruleid=ruleid, type='1')
            elif pl_envid == "2":
                jsonRes = search_liveSearch(instrumentid=instrumentid, direction=direction, legsettltype=legsettltype,
                                            tradeid=tradeid, ruleid=ruleid, type='1')
            return jsonRes
        elif request.POST.get('daySearchPosition_search', None):
            # 前端查询条件
            data = json.loads(request.POST.get("data"))
            instrumentid = data.get("instrumentid", None)  # if no condition value is str ''
            ruleid = data.get("ruleid", None)
            stgname = data.get("stgname", None)
            pl_envid = data.get("pl_envid", None)
            if pl_envid == "1":  # 仿真环境
                jsonRes = search_daySearch(instrumentid=instrumentid, stgname=stgname, ruleid=ruleid, type='2')
            elif pl_envid == "2":
                jsonRes = search_liveSearch(instrumentid=instrumentid, stgname=stgname, ruleid=ruleid, type='2')
            return jsonRes

        elif request.POST.get("daySearchInput_search", None):
            # 前端查询条件
            data = json.loads(request.POST.get("data"))
            stgid = data.get("stgid", None)  # if no condition value is str ''
            envid = data.get("envid", None)
            bondid = data.get("bondid", None)
            customerid = data.get("customerid", None)
            direction = data.get("direction", None)
            settletype = data.get("settletype", None)
            if envid == "1":  # 仿真环境
                jsonRes = search_daySearch(direction=direction, legsettltype=settletype, ruleid=stgid,
                                           bondid=bondid, customerid=customerid, type="3")
            elif envid == "2":
                jsonRes = search_liveSearch(direction=direction, legsettltype=settletype, ruleid=stgid,
                                            bondid=bondid, customerid=customerid, type="3")
            return jsonRes
